﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Daq.Services;
using Daq.Utils;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.RichTextBoxUI;

namespace Daq.ViewModels.DeviceSettingsViewModels
{
    public partial class ChannelsViewModel : ObservableObject
    {
        [ObservableProperty]
        private DeviceService _deviceService;
        private readonly SettingsService _settings;
        private readonly ILogger logger;
        private readonly IDialogService dialogService;
        public ChannelsViewModel(DeviceService deviceService, IDialogService dialogService, SettingsService settings, ILogger logger)
        {
            DeviceService = deviceService;
            _settings = settings;
            this.dialogService = dialogService;
            this.logger = logger;
        }


        [RelayCommand]
        private async Task Connect()
        {
            if (DeviceService.Daq != null && DeviceService.Daq.Status != DaqWorkStatus.Disconnected) return; 
            logger.Information("连接设备");
            if(_settings.Devices == null)
            {
                logger.Information("设备列表为空，不连接");
                return;
            }
            IsBusy = true;
            BusyContent = "获取通道参数";
            await Task.Delay(500);
            //try
            {
                await DeviceService.OpenDevices(_settings.Devices);
                //var info = await DeviceService.GetChannelsInfoAsync();
                //Daqs = DeviceService.Daqs;
                //var settings = Daqs.Select(d => d.DaqSettings);
                //foreach(var setting in settings)
                //{
                //    DaqSettings.Add(setting);
                //}
            }
            //catch(Exception ex)
            {
                //logger.Information($"连接失败：{ex.Message}");
            }

            IsBusy = false;
            BusyContent = "";
        }

        //[ObservableProperty]
        //private ObservableCollection<DaqBase>? daqs;

        [ObservableProperty]
        private bool isBusy;

        [ObservableProperty]
        private string? busyContent;

        [RelayCommand]
        private void GenerateRandomChannelColor()
        {
            int count = 0;
            foreach (var daq in DeviceService.Devices)
            {
                if (daq == null) continue;
                if (daq.Channels == null) continue;
                foreach(var ch in daq.Channels)
                {
                    count++;
                    ch.Color = ColorGenerator.GenerateRandomColorWithBrightness(255, 255);
                }
            }
            var colors = ColorGenerator.GenerateRandomColors(count);
            if (colors == null || colors.Count != count) return;
            count = 0;
            foreach (var daq in DeviceService.Devices)
            {
                if (daq == null) continue;
                if (daq.Channels == null) continue;
                foreach (var ch in daq.Channels)
                {
                    ch.Color = colors[count++];
                }
            }
        }

        [RelayCommand]
        private void EnableSelectedChannels()
        {
            foreach (var sn in selectedChannels.Keys)
            {
                if (selectedChannels.TryGetValue(sn, out var value))
                {
                    if (value == null) continue;
                    foreach (var ch in value)
                    {
                        if (ch is DaqChannelInfo info)
                        {
                            info.Status = true;
                        }
                    }
                }
            }
        }

        [RelayCommand]
        public void DisableSelectedChannels()
        {
            foreach(var sn in selectedChannels.Keys)
            {
                if(selectedChannels.TryGetValue(sn, out var value))
                {
                    if (value == null) continue;
                    foreach(var ch in value)
                    {
                        if(ch is DaqChannelInfo info)
                        {
                            info.Status = false;
                        }
                    }
                }
            }
        }

        [RelayCommand]
        private async Task ClearConfiguration()
        {
            if(await dialogService.ShowConfirmationAsync("确认清除", "确认清除配置缓存？") == false)
            {
                return;
            }
            await DeviceService.ClearSettings();
            await Connect();
        }

        private Dictionary<string, ObservableCollection<object>?> selectedChannels = new ();

        [RelayCommand]
        public void SelectionChanged(Tuple<string, object> param)
        {
            string sn = param.Item1;
            ObservableCollection<object>? infos = param.Item2 as ObservableCollection<object>;

            if (string.IsNullOrWhiteSpace(sn)) return;
            if(selectedChannels.ContainsKey(sn))
            {
                selectedChannels[sn] = infos;
            }
            else
            {
                selectedChannels.Add(sn, infos);
            }
        }

        [RelayCommand]
        private async Task Save()
        {
            await SaveChannelSettings();
        }

        private async Task<bool> SaveChannelSettings()
        {
            bool result = true;
            IsBusy = true;
            BusyContent = "保存通道参数";
            try
            {
                DeviceService.CheckChannelNames();
                await DeviceService.SaveSettings();
                await Task.Delay(500);
            }
            catch(Exception ex)
            {
                await dialogService.ShowMessageAsync("错误", $"通道参数保存失败:{ex.Message}");
                result = false;
            }
            IsBusy = false;
            BusyContent = "";
            return result;
        }

        [RelayCommand]
        private async Task GoToNextStep()
        {
            if(DeviceService.Devices == null)
            {
                await dialogService.ShowMessageAsync("错误", "设备列表为空");
                return;
            }
            List<string> channelNames = [];
            foreach(var daq in DeviceService.Devices)
            {
                if (daq.Channels == null) continue;
                foreach(var ch in daq.Channels)
                {
                    if (!ch.IsEnabled) continue;
                    if(ch.Alias == null || string.IsNullOrWhiteSpace(ch.Alias))
                    {
                        await dialogService.ShowMessageAsync("错误", "通道名称不能为空");
                        return;
                    }
                    if(channelNames.Contains(ch.Alias))
                    {
                        await dialogService.ShowMessageAsync("错误", $"通道名称{ch.Alias}重复");
                        return;
                    }
                    channelNames.Add(ch.Alias);
                }
            }
            
            //if (await SaveChannelSettings())
            {
                var vm = App.Current.Services.GetService<DeviceSettingsViewModel>();
                vm?.SelectStep("测量设置");
            }
        }

        [RelayCommand]
        private void GoToPreviousStep()
        {
            var vm = App.Current.Services.GetService<DeviceSettingsViewModel>();
            vm?.SelectStep("连接设置");
        }
    }
}
